<template>
  <div>
    <div class="content-title title-wrapper">
      <span>关联商品</span>
      <el-button
        class="operate-btn"
        type="primary"
        size="mini"
        @click="add"
        :disabled="disabled"
      >
        添加商品
      </el-button>
      <span class="warning-tip">
        内部商品折扣最低{{ fcProductDiscount }}折, 外采商品不限制折扣范围
      </span>
    </div>

    <el-form :model="formModel" ref="form" :disabled="disabled">
      <!-- 这里一定是 传递一个数组进去 -->
      <el-table border :data="formModel.list">
        <el-table-column min-width="200px" label="商品名称">
          <template #default="{ row }">
            <span v-if="row.itemType === 1" class="sign-icon fc-pick-sign-icon"
              >内部</span
            >
            <span v-else class="sign-icon outside-pick-sign-icon">外采</span>
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :align="disabled ? 'right' : 'left'"
          min-width="120px"
          label="使用数量"
        >
          <template #default="{ row, $index }">
            <el-form-item
              v-if="!disabled"
              :prop="'list.' + $index + '.usageAmount'"
              :rules="rules.usageAmount"
            >
              <el-input :maxlength="4" v-model="row.usageAmount" />
            </el-form-item>

            <span v-else>{{ row.usageAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :align="disabled ? 'right' : 'left'"
          min-width="160px"
          label="权益次数"
        >
          <template #default="{ row, $index }">
            <el-form-item
              v-if="!disabled"
              :prop="'list.' + $index + '.usageCount'"
              :rules="rules.usageCount"
            >
              <el-input :maxlength="4" v-model="row.usageCount" />
            </el-form-item>

            <!-- 详情状态只显示数字 -->
            <span v-else>{{ row.usageCount }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="160px" label="权益方式">
          <template #default="{ row }">
            <el-select
              class="el-form-item-select"
              v-if="!disabled"
              v-model="row.equityMethod"
              @change="(value) => handleEquityMethod(value, row)"
            >
              <el-option label="固定权益价" :value="0"> </el-option>
              <el-option label="固定折扣" :value="1"> </el-option>
            </el-select>

            <span v-else>{{ showEquityMethod(row.equityMethod) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          min-width="160px"
          label="单次权益价/折扣"
          :align="disabled ? 'right' : 'left'"
        >
          <template #default="{ row, $index }">
            <el-form-item
              v-if="row.equityMethod === 0"
              :prop="'list.' + $index + '.unitPrice'"
              :rules="rules.unitPrice"
            >
              <el-input
                v-if="!disabled"
                style="width: 100px"
                type="number"
                v-model="row.unitPrice"
              />

              <span v-else>{{ row.unitPrice }}</span
              >元
            </el-form-item>
            <el-form-item
              v-if="row.equityMethod === 1"
              :prop="'list.' + $index + '.discount'"
              :rules="getDiscountRules(row.itemType)"
            >
              <el-input
                v-if="!disabled"
                style="width: 100px"
                type="number"
                v-model="row.discount"
              />
              <span v-else>{{ row.discount }}</span
              >折
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          min-width="160px"
          label="单次权益收入"
          :align="disabled ? 'right' : 'left'"
        >
          <template slot="header">
            单次权益收入
            <el-tooltip
              class="item"
              effect="dark"
              content="关联的所有服务/商品/套餐行的权益次数*单次权益收入加总需等于权益卡销售价"
              placement="top-start"
            >
              <i class="el-icon-warning"></i>
            </el-tooltip>
          </template>
          <template slot-scope="{ row, $index }">
            <el-form-item
              v-if="!disabled"
              :prop="'list.' + $index + '.equityIncome'"
              :rules="rules.equityIncome"
            >
              <el-input
                style="width: 100px"
                type="number"
                v-model="row.equityIncome"
              />
              元
            </el-form-item>
            <span v-else>{{ row.equityIncome }}元</span>
          </template>
        </el-table-column>
        <el-table-column v-if="!disabled" fixed="right" label="操作">
          <template #default="{ row }">
            <el-button type="text" @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash-es'
import Big from 'big.js'
import { Random } from 'mockjs'

import { checkNum, checkDiscount, discountValidate, limitUsageCount, limitFcDiscount } from './rules'

export default {
  name: 'relateGoods',
  props: {
    list: {
      type: Array,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    },
    rightsCardCount: {
      type: [String, Number]
    },
    /**
    * 内部商品折扣 - 可动态配置
    */
    fcProductDiscount: {
      type: [String, Number]
    }
  },
  data () {
    return {
      isShow: false,
      formModel: {
        list: []
      },
      rules: {}
    }
  },
  watch: {
    'formModel.list': {
      handler () {

        // 注意这里一定要用 nextTick 否则，在删除数据的时候，父组件行数据是删除了，但是form中针对table某个进行数据校验，就会出现找不到那一行数据的情况
        this.$nextTick(() => {
          this.summary()
        })
      },
      deep: true
    },
    // 监控这里是因为 接口是异步的
    fcProductDiscount () {
      this.generageRules(this.rightsCardCount)
    }
  },
  created () {
    this.formModel.list = this.list

    this.generageRules(this.rightsCardCount)
  },

  methods: {
    /**
     * 权益方式
     */
    showEquityMethod (type) {
      return type === 0 ? '固定权益价' : '固定折扣'
    },

    /**
     * 动态生成规则
     */
    generageRules (count) {
      let rules = {
        usageAmount: [
          {
            required: true,
            message: '次数不能为空',
            trigger: ['change', 'blur']
          },
          {
            validator: checkNum,
            trigger: ['change', 'blur']
          }
        ],
        usageCount: [
          {
            required: true,
            message: '次数不能为空',
            trigger: ['change', 'blur']
          },
          {
            validator: checkNum,
            trigger: ['change', 'blur']
          },
          {
            validator: limitUsageCount(count),
            trigger: ['change', 'blur']
          }
        ],
        unitPrice: [
          {
            required: true,
            message: '单次权益价不能为空',
            trigger: ['change', 'blur']
          },
          {
            validator: checkDiscount,
            trigger: ['change', 'blur']
          }
        ],
        equityIncome: [
          {
            required: true,
            message: '单次权益收入不能为空',
            trigger: ['change', 'blur']
          },
          {
            validator: checkDiscount,
            trigger: ['change', 'blur']
          }
        ]
      }

      this.rules = rules
    },

    /**
     * @params {Number} itemType 1-内部商品， 0外采商品
     * @description 外采商品对折扣没有限制
     */
    getDiscountRules (itemType) {
      let baseRules = [
        {
          required: true,
          message: '单次权益折扣不能为空',
          trigger: ['change', 'blur']
        },
        {
          validator: discountValidate,
          trigger: ['change', 'blur']
        }
      ]

      if (itemType === 1) {
        baseRules.push(
          {
            validator: limitFcDiscount(this.fcProductDiscount),
            trigger: ['change', 'blur']
          }
        )
      }

      return baseRules
    },
    /**
     * 汇总
     * @description 组件对外提供计算好的数据直接使用
     * ∑（权益次数 * 单次权益收入）
     */
    summary () {
      let isOk = true

      this.$refs['form'].validate((valid, failField) => {
        if (!valid) {
          isOk = false
          console.log('关联商品表格校验失败', failField)
        }
      })

      if (!isOk) return

      let list = cloneDeep(this.formModel.list)

      let total = list.reduce((prevTotal, current) => {
        // 需要对这块的内容进行容错处理
        let rowSum = Big(current.usageCount || 0).times(current.equityIncome || 0)
        return Big(prevTotal).add(rowSum).toNumber()
      }, 0)

      this.$emit('updateSum', total)
    },
    add () {
      this.updateList({
        productId: Random.guid(),
        name: Random.ctitle(),
        // 商品类型
        itemType: Random.integer(0, 1)
      })
    },

    remove (row) {
      this.formModel.list = this.formModel.list.filter(item => item.productId !== row.productId)
    },
    updateList (rowInfo) {
      rowInfo.usageType = 0
      rowInfo.usageAmount = 0
      rowInfo.usageCount = 0
      rowInfo.equityMethod = 0
      rowInfo.unitPrice = 0
      rowInfo.discount = 0
      rowInfo.equityIncome = 0

      this.formModel.list.push(rowInfo)
    },

    resetFields (formName, key) {
      this.$refs[formName].clearValidate(key)
    },

    /**
     * 切换权益方式，重置相斥的内容
     */
    handleEquityMethod (value, row) {
      if (value === 0) {
        row.discount = 0
      } else {
        row.unitPrice = 0
      }

      this.$nextTick(() => {
        this.$refs['form'].clearValidate(['discount', 'unitPrice'])
      })
    },

    /**
     * @description 通过 ref 提供给父组件调用
     */
    getCheckResult () {
      let isOk = true

      this.$refs['form'].validate((valid, failField) => {
        if (!valid) {
          console.warn(`关联商品校验失败`, failField)
        }

        isOk = valid
      })

      return isOk
    },
    /**
     * 通过ref 提供给父组件调用
     */
    getFormModel () {
      return cloneDeep(this.formModel.list)
    }
  }
}
</script>
<style lang="less" scoped>
.title-wrapper {
  display: flex;
  align-items: center;

  .operate-btn {
    margin: 0 8px;
  }

  .warning-tip {
    color: #aaa;
    font-size: 14px;
    font-weight: normal;
  }
}

.sign-icon {
  padding: 2px 8px;
  margin-right: 8px;
  border-radius: 2px;
  font-size: 12px;
  text-align: center;
}
.fc-pick-sign-icon {
  background: #1989fa;
  color: #fff;
}
.outside-pick-sign-icon {
  background: #fff;
  color: #1989fa;
  border: 1px solid #1f88ee;
}
// 解决：表格存在校验 select 又不存在校验的时候， 不是水平对齐
.el-form-item-select {
  margin-bottom: 16px;
}
</style>
